/**
 * 封装uni缓存相关方法
 */

/**
 * 设置缓存
 * @param key 缓存键
 * @param data 缓存数据
 * @param expire 过期时间（毫秒）
 */
export const setStorage = (key: string, data: any, expire?: number): void => {
  const storage = {
    data: data,
    expire: expire ? new Date().getTime() + expire : null
  };
  uni.setStorageSync(key, JSON.stringify(storage));
};

/**
 * 获取缓存
 * @param key 缓存键
 * @returns 缓存数据，过期或不存在则返回null
 */
export const getStorage = (key: string): any => {
  const storage = uni.getStorageSync(key);
  if (!storage) return null;
  
  try {
    const storageObj = JSON.parse(storage);
    // 判断是否过期
    if (storageObj.expire && storageObj.expire < new Date().getTime()) {
      uni.removeStorageSync(key);
      return null;
    }
    return storageObj.data;
  } catch (e) {
    return null;
  }
};

/**
 * 移除缓存
 * @param key 缓存键
 */
export const removeStorage = (key: string): void => {
  uni.removeStorageSync(key);
};

/**
 * 清空所有缓存
 */
export const clearStorage = (): void => {
  uni.clearStorageSync();
};

/**
 * 获取所有缓存信息
 */
export const getStorageInfo = (): UniApp.GetStorageInfoSuccess => {
  return uni.getStorageInfoSync();
}; 